package com.techstar.mqttprocesser.service.mqtt.handler.message;

import com.alibaba.fastjson.JSON;
import com.techstar.mqttprocesser.service.mqtt.config.DataParseMapConfig;
import com.techstar.mqttprocesser.service.mqtt.config.LogConfig;
import com.techstar.mqttprocesser.service.mqtt.config.MqttClientProperties;
import com.techstar.mqttprocesser.service.mqtt.handler.MqttServiceRegistry;
import com.techstar.mqttprocesser.service.mqtt.handler.device.DeviceDataParse;
import com.techstar.mqttprocesser.service.mqtt.handler.device.DeviceDataParseFactory;
import com.techstar.mqttprocesser.service.mqtt.mapper.MqttJsonDataModelMapper;
import com.techstar.mqttprocesser.service.mqtt.model.*;
import com.techstar.mqttprocesser.service.mqtt.utils.JsonDataParseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 数据消息处理器
 * @author lilei
 * @create 2025-03-27-2025/3/27
 */
@Slf4j
@Component
public class DataMessageHandler implements MessageHandler {

    @Autowired
    private LogConfig logConfig;

    @Autowired
    private MqttJsonDataModelMapper mqttJsonDataModelMapper;

    @Autowired
    private DeviceDataParseFactory deviceDataParseFactory;

    @Override
    public TopicType getTopicType() {
        return TopicType.data;
    }

    @Override
    public void handleMessage(String deviceName, MqttClientProperties.TopicConfig topicConfig, String message) {
        try {
            List<MqttJsonParseConfig> mqttJsonParseConfig = DataParseMapConfig.getJsonParseConfig(deviceName, topicConfig.getTopic());
            if (mqttJsonParseConfig == null) {
                log.error("未找到设备{}的解析配置", deviceName);
                return;
            }

            // 解析数据
            List<MqttJsonDataModel> mqttJsonDataModels = new ArrayList<>();
            for (MqttJsonParseConfig config : mqttJsonParseConfig) {
                try {
                    MqttJsonDataModel mqttJsonDataModel = new MqttJsonDataModel();
                    mqttJsonDataModel.setDeviceName(deviceName);
                    mqttJsonDataModel.setTopic(topicConfig.getTopic());

                    // 解析数据
                    JsonSingleModle singleModle = JsonDataParseUtil.parseJsonData(message, config);
                    if (config.getRequired() == 0 && (singleModle.getValue() == null  || "null".equals(singleModle.getValue()))){
                        // 非必须字段，且解析结果为空，不保存
                        continue;
                    }

                    mqttJsonDataModel.setField(singleModle.getKey());
                    mqttJsonDataModel.setValue(singleModle.getValue());

                    //添加时间戳
                    DeviceDataParse messageHandler = deviceDataParseFactory.getMessageHandler(DeviceType.getByCode(deviceName));
                    LocalDateTime localDateTime = messageHandler.parseDataTime(message);
                    mqttJsonDataModel.setDataTime(localDateTime);

                    // 添加到列表
                    mqttJsonDataModels.add(mqttJsonDataModel);
                }catch (Exception e){
                    log.error("解析数据失败, deviceName: {}, topic: {}, clientId: {}, message: {}, config: {}", deviceName, topicConfig.getTopic(), MqttServiceRegistry.getClient(deviceName).getClientId(), message, JSON.toJSONString(config), e);
                    continue;
                }
            }

            // 保存数据
            mqttJsonDataModelMapper.insertOrUpdate(mqttJsonDataModels);

            if (logConfig.debugLog()){
                log.info("保存数据: {}", JSON.toJSONString(mqttJsonDataModels));
            }

        }catch (Exception e){
            log.error("处理数据消息失败, deviceName: {}, topic: {}, clientId: {}, message: {}", deviceName, topicConfig.getTopic(), MqttServiceRegistry.getClient(deviceName).getClientId(), message, e);
        }
    }
}
